<?php
require_once dirname(__FILE__).'/../lib/userGeneratorConfiguration.class.php';
require_once dirname(__FILE__).'/../lib/userGeneratorHelper.class.php';

class userActions extends autoUserActions {
  
  public function executeLogin() {
    $this->form = new LoginForm();
    $this->email = $this->getRequestParameter('email');
    $this->password = md5($this->getRequestParameter('password')); 
    
    if ($this->request->isMethod('POST') && $this->email && $this->password) {
      $this->user = Doctrine::getTable('AimUser')->findOneBy('email', $this->email);    
      
      // Tài khoản không tồn tại
      if (!$this->user) {
        return sfView::SUCCESS;
      }
      
      // Cái này dùng để phục vụ autocomplete thôi 
      if (false) $this->user = new AimUser();
      
      // Sai mật khẩu
      if ($this->user->getPassword()!=$this->password) {
        #$this->getUser()->setFlash('msg_error_login', 'Sai mật khẩu.');
        $this->form->setDefault('email', $this->email);
        return sfView::SUCCESS;
      } else {
        // dau's
        $role = (int)$this->user->getRole();
        # Lấy id role của user nếu là superadmin(1) và admin(2) thì pass
        if ($role==1 || $role==2) {
          $this->getUser()->login($this->user);
          $this->redirect('homepage');
        } else {
          return sfView::SUCCESS;
        }
      }
    }
  }
  
  /**
   * 
   * Enter description here ...
   * @param sfWebRequest $request
   */
  public function executeLogout(sfWebRequest $request) {
    $this->getUser()->logout();
    $this->redirect('homepage');
  }
  
  /**
   * 
   * Enter description here ...
   * @param sfWebRequest $request
   */
  public function executePermission(sfWebRequest $request) {
    $this->user_id = $request->getParameter('id');
    $this->user = AimUserTable::getInstance()->find(array($this->user_id));
    $this->forward404Unless($this->user);
    
    $this->form = new UserPermissionForm($this->user_id);
    
    $params = $request->getParameter($this->form->getName());
    if ($params) {
      unset($params['_csrf_token']);
      AimUserPermissionTable::getInstance()->setUserPermissions($this->user_id, $params);
      $this->redirect('user/index');
    }
  }
  
  protected function processForm(sfWebRequest $request, sfForm $form)
  {
    // dau's
    $check = false;
    $checkuser = false;
    if ($form->isNew())
      $form->configureNewUser();
    $params = $request->getParameter($form->getName());
    $form->bind($params, $request->getFiles($form->getName()));
    if ($form->isValid())
    {
      $notice = $form->getObject()->isNew() ? 'The item was created successfully.' : 'The item was updated successfully.';

      try {
        // dau's
        $pass   = $params['new_password'];
        $cpass = $params['confirm_password'];        
        
        if (isset($pass) && ($pass!='') && ($pass==$cpass)) {
          $users =  AimUserTable::getInstance()->findOneBy('email', $params['email']);          
          
          if ($users && $form->isNew()){
            $checkuser = true;
          } else {
            $params['password'] = md5($pass);
            $form->bind($params, $request->getFiles($form->getName())); 
            $Aim_user = $form->save();
            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $Aim_user)));
          }
        } else {
          if (!$form->isNew()) {          
            $Aim_user = $form->save();
            $this->dispatcher->notify(new sfEvent($this, 'admin.save_object', array('object' => $Aim_user)));
          }
          if (!$pass=='') {
            $check = true;
          }          
        }
      } catch (Doctrine_Validator_Exception $e) {

        $errorStack = $form->getObject()->getErrorStack();

        $message = get_class($form->getObject()) . ' has ' . count($errorStack) . " field" . (count($errorStack) > 1 ?  's' : null) . " with validation errors: ";
        foreach ($errorStack as $field => $errors) {
            $message .= "$field (" . implode(", ", $errors) . "), ";
        }
        $message = trim($message, ', ');

        $this->getUser()->setFlash('error', $message);
        return sfView::SUCCESS;
      }
      if ($check) {
        $this->getUser()->setFlash('error', 'Error New Password != Confirm Password.');
        $this->setTemplate('new');  
      } else if ($checkuser) { 
        $this->getUser()->setFlash('error', 'Username already exists in database.');
        $this->setTemplate('new');  
      } else {      
        if ($request->hasParameter('_save_and_add'))
        {
          $this->getUser()->setFlash('notice', $notice.' You can add another one below.');
          $this->redirect('@Aim_user_new');
        }
        else
        {
          $this->getUser()->setFlash('notice', $notice);
          
          $this->redirect(array('sf_route' => 'Aim_user_edit', 'sf_subject' => $Aim_user));
        }
      }
    }
    else
    {
      $this->getUser()->setFlash('error', 'The item has not been saved due to some errors.', false);
    }
  }
}
